/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.di.wx.server.handler;

import cn.ac.iie.di.commons.httpserver.framework.handler.HandlerI;
import cn.ac.iie.di.commons.httpserver.framework.util.ParseRequestStream;
import cn.ac.iie.di.wx.server.common.RuntimeEnv;
import cn.ac.iie.di.wx.server.httpservice.HttpSender;
import cn.ac.iie.di.wx.server.vo.RedisVo;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.eclipse.jetty.server.Request;

/**
 *
 * @author Administrator
 */
public class DelUserFriendCircleMonitorByUserIdHandler implements HandlerI {

    static Logger logger = Logger.getLogger(DelUserFriendCircleMonitorByUserIdHandler.class.getName());

    @Override
    public void init() throws Exception {
    }

    @Override
    public void execute(Request pRequest, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String delUFCMonitor = ParseRequestStream.parseRequestStreamAsString(pRequest.getInputStream());
        logger.info("DelUserFriendCircleMonitorByUserIdHandler request is:" + delUFCMonitor);
        try {
            JSONObject addUFCMonitorJson = JSONObject.parseObject(delUFCMonitor);
            String opid = addUFCMonitorJson.getString("opid");//存redis里，将关键字存value里面
            //redis存key=pyq_opid,value=useridValue
            //新加一接口，必须同时包含userid，accountnameValue
            String useridValue = "";
            String accountnameValue = "";
            JSONArray param = addUFCMonitorJson.getJSONArray("param");
            Object removeobj = null;
            for (int i = 0; i < param.size(); i++) {
                JSONObject obi = param.getJSONObject(i);
                if (obi.getString("name").equals("userid")) {
                    useridValue = obi.getString("value");
                    logger.info(useridValue);
                    removeobj = param.getJSONObject(i);
                }
                if (obi.getString("name").equals("accountname")) {
                    accountnameValue = obi.getString("value");
                    logger.info(accountnameValue);
                }
            }
            //由于fh接口只能接收一个参数，选定accountname作为保留参数进行发送，将userid去掉
            boolean flag = param.remove(removeobj);
            logger.info("remove userid " + flag + ",and request send to fh is " + addUFCMonitorJson.toJSONString());

            if (!useridValue.equals("") || useridValue != null) {
                RuntimeEnv.redisVos.put(new RedisVo("bcp_" + opid, useridValue));
                logger.info("put into redisVos queue,key = \"bcp_\"" + opid + ",value = " + useridValue);

            } else {
                logger.info("userid is null in this request");
            }
            if (!accountnameValue.equals("") || accountnameValue != null) {
                RuntimeEnv.redisVos.put(new RedisVo("acc_" + accountnameValue, useridValue));
                logger.info("put into redisVos queue,key = \"acc_\"" + accountnameValue + ",value = " + useridValue);

            } else {
                logger.info("accountnameValue is null in this request");
            }

            addUFCMonitorJson.put("areaid", (String) RuntimeEnv.getParam(RuntimeEnv.areaid));
            addUFCMonitorJson.put("userareaid", (String) RuntimeEnv.getParam(RuntimeEnv.userareaid));
            addUFCMonitorJson.put("sysid", (String) RuntimeEnv.getParam(RuntimeEnv.sysid));
            addUFCMonitorJson.put("sysuserid", (String) RuntimeEnv.getParam(RuntimeEnv.sysuserid));
            logger.info(addUFCMonitorJson.toJSONString());
//            RuntimeEnv.redisVos.put(new RedisVo(opid, param));
            //获取响应,post，请求格式和发送方法
            HttpSender hs = new HttpSender();
            String responseStr = hs.closableHttpClient(addUFCMonitorJson.toJSONString(), (String) RuntimeEnv.getParam(RuntimeEnv.delUserFriendCircleMonitor));
            if (responseStr.equals("")) {
                logger.info("DelUserFriendCircleMonitorByUserIdHandler response is null");
                responseStr = "{\"opid\": \"" + opid + "\",\"desc\": \"err烽火超时异常\",\"frontnum\": -1,\"status\": \"404\"}";;
            } else {
                logger.info("DelUserFriendCircleMonitorByUserIdHandler response is sucess:" + responseStr);

                try {

                    JSONObject jSONObject = JSONObject.parseObject(responseStr);
                    String frontnum = jSONObject.getString("frontnum");
                    String status = jSONObject.getString("status");
                    if (status.equals("200")) {
                        //状态正常
                        if (frontnum.equals("0")) {
                            logger.info("DelUserFriendCircleMonitorByUserIdHandler reponse is 200");
                        } else {
                            logger.info("DelUserFriendCircleMonitorByUserIdHandler该布控号正在排队中");
                        }
                    } else {
                        logger.info("DelUserFriendCircleMonitorByUserIdHandler请求状态不正常");
                    }
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
            }
            //给客户端发送响应消息
            byte[] bytesContent = new byte[1024 * 2];
            int bytesReadIn = 0;
            ServletOutputStream out = response.getOutputStream();
            BufferedOutputStream bos = new BufferedOutputStream(out);
            InputStream inputStream = new ByteArrayInputStream(responseStr.getBytes("UTF-8"));
            while ((bytesReadIn = inputStream.read(bytesContent, 0, 1024 * 2)) > 0) {
                bos.write(bytesContent, 0, bytesReadIn);
            }
            RuntimeEnv.delUFCMCount.getAndIncrement();
            bos.flush();
            bos.close();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

}
